package cn.it.shop.dao.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.classic.Session;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Repository;

import cn.it.shop.dao.PrivilegeDao;
import cn.it.shop.pojo.Privilege;

@Repository("privilegeDao")
@SuppressWarnings("unchecked")
public class PrivilegeDaoImpl extends BaseDaoImpl<Privilege> implements
		PrivilegeDao {

	private Map<String, Collection<ConfigAttribute>> privilegeRoleMap = new HashMap<String, Collection<ConfigAttribute>>();

	@Override
	public List<Privilege> queryForTree() {
		String hql = null;
		// 1: 查询所有父菜单
		hql = "FROM Privilege p WHERE p.parent IS NULL";
		// 2: 查询某个菜单和它的子菜单集合
		hql = "SELECT DISTINCT p FROM Privilege p LEFT JOIN FETCH p.childrenSet WHERE p.id=1";
		// 3: 查询所有父菜单和它子菜单集合
		hql = "SELECT DISTINCT p FROM Privilege p LEFT JOIN FETCH p.childrenSet WHERE p.parent IS NULL";
		Session session = sessionFactory.openSession();
		return session.createQuery(hql) //
				.list();
	}

	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		FilterInvocation invocation = (FilterInvocation) object;
		String url = invocation.getRequest().getServletPath();
		return privilegeRoleMap.get(url);
	}

	public Collection<ConfigAttribute> getAllConfigAttributes() {
		System.out.println("-------------getAllConfigAttributes 项目启动的时候获取 URL与角色的关系, 只执行一次,以后授权要同步--------------------");
		Session session = sessionFactory.openSession();
		List<Privilege> privilegeslist = session.createQuery(
				"FROM Privilege p JOIN FETCH p.roleSet").list();
		for (Privilege privilege : privilegeslist) {
			privilegeRoleMap.put(privilege.getUrl(), privilege.getRoleSet());
		}
		return null;
	}

}
